package com.sys.basics.config.globalHandler;

import com.sys.basics.config.jsonRes.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.List;
import java.util.Set;

// 可以不用, 统一在MyGlobalErrorController中处理
@Slf4j
@RestControllerAdvice
public class MyGlobalExceptionHandler {
    protected JsonResult result = new JsonResult();

    /**
     * @author: ares
     * @date: 2021/9/28 21:52
     * @description: body参数对象校验 抛出 MethodArgumentNotValidException 异常
     * @param exception
     * @return
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public JsonResult validationBodyException(MethodArgumentNotValidException exception) {
        BindingResult bindingResult = exception.getBindingResult();
        StringBuilder stringBuilder = new StringBuilder();

        if (bindingResult.hasErrors()) {
            List<ObjectError> errorList = bindingResult.getAllErrors();
            errorList.forEach(error -> {
                stringBuilder.append(error.getDefaultMessage()).append(",");
            });
        }
        log.error(">>>body参数校验失败<<<: {}", stringBuilder.toString().substring(0, stringBuilder.lastIndexOf(",")));
        result.setCode(String.valueOf(HttpStatus.BAD_REQUEST.value()));
        result.setMessage(stringBuilder.toString().substring(0, stringBuilder.lastIndexOf(",")));
        return result;
    }


    /**
     * @author: ares
     * @date: 2021/9/28 21:55
     * @description: path参数校验 抛出 ConstraintViolationException 异常
     * @param exception
     * @return
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(ConstraintViolationException.class)
    public JsonResult validationPathException(ConstraintViolationException exception) {
        Set set = exception.getConstraintViolations();
        StringBuilder stringBuilder = new StringBuilder();
        if (!set.isEmpty()) {
            set.forEach(error -> {
                ConstraintViolation constraintViolation = (ConstraintViolation) error;
                stringBuilder.append(constraintViolation.getMessage()).append(",");
            });
        }
        log.error(">>>path参数校验失败<<<: {}", stringBuilder.toString().substring(0, stringBuilder.lastIndexOf(",")));
        result.setCode(String.valueOf(HttpStatus.BAD_REQUEST.value()));
        result.setMessage(stringBuilder.toString().substring(0, stringBuilder.lastIndexOf(",")));
        return result;
    }

}
